﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;
using HF.User.Data;
namespace HF.Permission.Data
{
    /// <summary>
    /// 数据访问类GroupData。
    /// </summary>
    public class GroupData
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "GroupId", "GroupName", "GroupDes" };
        private string tableName = "HF_Group";
        private string keyField = "GroupId";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(GroupEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@GroupId", entity.GroupId, typeof(string));
            sqlDataItem.AppendParameter("@GroupName", entity.GroupName, typeof(string));
            sqlDataItem.AppendParameter("@GroupDes", entity.GroupDes, typeof(string));
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public GroupEntity GetGroupEntity(DataRow dr)
        {
            GroupEntity entity = new GroupEntity();
            entity.GroupId = dr["GroupId"].ToString();
            entity.GroupName = dr["GroupName"].ToString();
            entity.GroupDes = dr["GroupDes"].ToString();
            return entity;
        }

        #endregion

        #region  构造函数
        public GroupData()
        { }
        public static GroupData GetInstance()
        {
            return new GroupData();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(GroupEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(GroupEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string groupId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, groupId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="groupId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string groupId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, groupId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="GroupId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetGroupTable(string groupId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, groupId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="groupId">主键Id</param>
        /// <returns>DataTable</returns>
        public GroupEntity GetGroupEntity(string groupId)
        {
            DataTable dt = GetGroupTable(groupId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetGroupEntity(dt.Rows[0]);
            }
            return null;
        }
       static bool IsGuidByReg(string strSrc)  
       {  
           try  
           {  
               Guid guid = new Guid(strSrc);  
               return true;  
           }  
           catch  
           {  
               return false;  
           }  
      }

        #endregion
        #region  扩展方法
        //此处添加扩展方法
        /// <summary>
        /// 获取所有组,按组名排序
        /// </summary>
        /// <returns>DataTable</returns>
        public DataTable GetAllGroups()
        {
            try
            {
                string tmpSql = "select * from HF_Group order by GroupName";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 获取所有组,按组名排序
        /// </summary>
        /// <returns>Entitys</returns>
        public List<GroupEntity> GetAllGroupEntitys()
        {
            try
            {
                List<GroupEntity> result = new List<GroupEntity>();
                DataTable dt = GetAllGroups();
                foreach (DataRow dr in dt.Rows)
                {
                    GroupEntity entity = GetGroupEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 根据组名查询租，模糊查询
        /// </summary>
        ///  <param name="groupName">组名</param>
        /// <returns>DataTable</returns>
        public DataTable GetGroupTableByName(string groupName)
        {
            try
            {
                string tmpSql = "select * from HF_Group where GroupName like @groupName";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.AppendParameter("@groupName", "%" + groupName + "%"); ;
                sqlItem.CommandText = tmpSql;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 根据组名查询租，模糊查询
        /// </summary>
        ///  <param name="groupName">组名</param>
        /// <returns>Entitys</returns>
        public List<GroupEntity> GetGroupEntitysByName(string groupName)
        {
            try
            {
                List<GroupEntity> result = new List<GroupEntity>();
                DataTable dt = GetGroupTableByName(groupName);
                foreach (DataRow dr in dt.Rows)
                {
                    GroupEntity entity = GetGroupEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 删除组,并删除组和用户之间的关系
        /// </summary>
        ///  <param name="groupName">组Id</param>
        /// <returns>操作返回码</returns>
        public bool DeleteGroup(string groupId)
        {
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_DeleteGroupPro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString().ToString();
                sqlItem.AppendParameter("@groupId", groupId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
                return true;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }



        /// <summary>
        /// 删除组中的所有用户 关系
        /// </summary>
        ///  <param name="groupId">组Id</param>
        /// <returns>操作返回码</returns>
        public bool RemoveUserOfGroup(string groupId)
        {
            try
            {
                string tmpSql = "delete  from HF_UserGroup where GroupId=@GroupId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@groupId", groupId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
                return true;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        /// <summary>
        /// 获得组的所有用户
        /// </summary>
        ///  <param name="groupId"></param>
        ///  <returns>DataTable</returns>
        public DataTable GetUsersOfGroup(string groupId)
        {
            try
            {
                string tmpSql = "";
                if (IsGuidByReg(groupId))
                {
                     tmpSql = "select * from HF_UserGroupView where GroupId=@GroupId";
                }
                else
                {
                    tmpSql = "select * from HF_UserGroupView where UserId=@GroupId";
                }
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.AppendParameter("@GroupId", groupId); ;
                sqlItem.CommandText = tmpSql;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 获得指定组中用户的分管副总
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserEntity GetUsersOfGroupAndDeptIds(string groupId, string deptId)
        {
            UserEntity entity = null;
            try
            {
                string tmpSql = "select  UserId,UserName,UserSex,UserPassword,UserTelephone,UserFax,UserEmail,UserChgPW,UserDepart,UserDes,UserStop,UserMsgAcept,UserQQ,UserMsn,PostID from v_UrereRolebyDeptlds  where RoleID=@GroupId and charindex(@DeptId,DeptIds)>0";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.AppendParameter("@GroupId", groupId);
                sqlItem.AppendParameter("@DeptId", deptId);
                sqlItem.CommandText = tmpSql;
                ClientDBAgent agent = new ClientDBAgent();
                DataTable dt = agent.ExecuteDataTable(sqlItem);
                if (dt.Rows.Count > 0) 
                {
                    DataRow dr = dt.Rows[0];
                     entity = UserData.GetInstance().GetUserEntity(dr);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return entity;
        }
        /// <summary>
        /// 获得组的所有用户
        /// </summary>
        ///  <param name="groupId"></param>
        ///  <returns>UserEntityS</returns>
        public List<UserEntity> GetUserEntitysOfGroup(string groupId)
        {
            List<UserEntity> result = new List<UserEntity>();
            DataTable dt = GetUsersOfGroup(groupId);
            foreach (DataRow dr in dt.Rows)
            {
                UserEntity entity = UserData.GetInstance().GetUserEntity(dr);
                result.Add(entity);
            }
            return result;
        }
        /// <summary>
        /// 把一个用户添加到一个组中。
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="groupId">组Id</param>
        /// <returns>是否成功</returns>
        public bool MoveUserIntoGroup(string userId, string groupId)
        {
            try
            {
                string tmpSql = "insert into HF_UserGroup(GroupId,UserId)values (@GroupId,@UserId)";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@GroupId", groupId);
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <summary>
        /// 根据UserId列出用户所隶属的所有组
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetGroupsOfUser(string userId)
        {
            try
            {
                string tmpSql = "select * from HF_UserGroupView where UserId=@UserId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.AppendParameter("@UserId", userId);
                sqlItem.CommandText = tmpSql;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 根据UserId列出用户所隶属的所有组
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns>GroupEntitys</returns>
        public List<GroupEntity> GetGroupEntitysOfUser(string userId)
        {
            try
            {
                List<GroupEntity> result = new List<GroupEntity>();
                DataTable dt = GetGroupsOfUser(userId);
                foreach (DataRow dr in dt.Rows)
                {
                    GroupEntity entity = GetGroupEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 删除用户隶属的所有组关系
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns>是否成功</returns>
        public bool RemoveGroupOfUser(string userId)
        {
            try
            {
                string tmpSql = "delete  from HF_UserGroup where UserId=@UserId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@UserId", userId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        #endregion
        #endregion
    }
}

